﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Configuration;

namespace ZPod.MTG.Windows
{
	public static class CardStorage
	{
		#region Private Properties
		
		private static string _currentPicturesDirectory;
		private static Dictionary<String, String> _cardsURL = new Dictionary<String, String>();
		private static List<String> _missingCards = new List<string>();
		private static int ThumbnailReductionFactor;
		
		#endregion

		#region Constants

		private const string GenericCardFileName = "__GenericCard__";
		private const string PicruresDirectory = "MTGPictures";
		private const string CardInfoURL = "http://magiccards.info/card.php?card={0}";
		private const string CardPictureURL = "http://magiccards.info/{0}{1}";
		private const string PathToPictures = "scans/en/";
		private const string ThumbnailSuffix = "_thumb";

		#endregion

		#region Static Constructor

		static CardStorage()
		{
			ThumbnailReductionFactor = 4;
			try
			{
				int factor = Int32.Parse(ConfigurationSettings.AppSettings["ThumbnailReductionFactor"]);

				if (factor > 0)
				{
					ThumbnailReductionFactor = factor;
				}
			}
			catch
			{
			}
			var currentDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
			var picDir = Path.Combine(currentDir, PicruresDirectory);
			if (!Directory.Exists(picDir))
			{
				Directory.CreateDirectory(picDir);
			}

			_currentPicturesDirectory = picDir;
		}

		#endregion

		#region Public Methods

		public static string GetGenericCard()
		{
			string genericCardPathFile = Path.Combine(_currentPicturesDirectory, GenericCardFileName);
			if (!File.Exists(genericCardPathFile))
			{
				Image.FromHbitmap(Properties.Resources.GenericCard.GetHbitmap()).Save(genericCardPathFile);
			}

			return genericCardPathFile;
			
		}

		public static String GetCardThumbnail(Card card)
		{
			return GetCardPicture(card) + ThumbnailSuffix;
		}

		public static String GetCardPicture(Card card)
		{
			if (String.IsNullOrEmpty(card.Name))
			{
				return GetGenericCard();
			}

			string cardFile = Path.Combine(_currentPicturesDirectory, card.Name);
			if (File.Exists(cardFile))
			{
				return cardFile;
			}
			else if (_missingCards.Contains(card.Name))
			{
				return GetMissingCard(card);
			}
			else
			{
				string url = GetCardPictureURL(card.Name);
				if (url.Length > 0)
				{
					try
					{
						using (WebClient client = new WebClient())
						{
							client.DownloadFile(url, cardFile);

							var image = Image.FromFile(cardFile);
							var thumbnail = image.GetThumbnailImage(image.Width / ThumbnailReductionFactor, image.Height / ThumbnailReductionFactor, () => false, IntPtr.Zero);
							thumbnail.Save(cardFile + ThumbnailSuffix);
							return cardFile;
						}
					}
					catch (Exception ex)
					{
						return GetMissingCard(card, ex.Message);
					}
				}
				else
				{
					return GetMissingCard(card);
				}
			}
		}

		#endregion

		#region Private Methods

		private static string GetMissingCard(Card card)
		{
			return GetMissingCard(card, "NO INFO");
		}

		private static string GetMissingCard(Card card, string message)
		{
			Debug.WriteLine(String.Format("ERROR LOADING PICTURE '{0}': {1}", card.Name, message));
			if (!_missingCards.Contains(card.Name))
			{
				_missingCards.Add(card.Name);
			}

			return GetGenericCard();
		}

		private static string GetCardPictureURL(string cardName)
		{
			if (!_cardsURL.ContainsKey(cardName))
			{
				string url = String.Format(CardInfoURL, cardName);
				using (WebClient client = new WebClient())
				{
					try
					{
						string fileContent = client.DownloadString(url);
						int pos = fileContent.IndexOf(PathToPictures);

						if (pos >= 0)
						{
							pos += PathToPictures.Length;
						}

						fileContent = fileContent.Substring(pos);
						pos = fileContent.IndexOf("\"");

						string pictureFile = fileContent.Substring(0, pos);

						_cardsURL[cardName] = String.Format(CardPictureURL, PathToPictures, pictureFile);

					}
					catch
					{
						return String.Empty;
					}
				}
			}

			return _cardsURL[cardName];
		}

		#endregion
	}
}
